﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace VueAdminService.Utils
{
	public class TokenUtil
	{
		/// <summary>
		/// 生成token
		/// </summary>
		/// <param name="userId">用户id</param>
		/// <param name="issuer">发行人</param>
		/// <param name="audience">接收者</param>
		/// <param name="key">密匙</param>
		/// <param name="expires">过期时间(分钟)</param>
		/// <returns></returns>
		public static string GenerateJwtToken(string userId, string issuer, string audience, string key, int expires = 30)
		{
			var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
			var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

			var claims = new[]
			{
				new Claim(JwtRegisteredClaimNames.Sub, userId),
				//new Claim(JwtRegisteredClaimNames.Exp,DateTime.Now.AddMinutes(expires).Ticks.ToString()),
				new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(expires)).ToUnixTimeSeconds()}"),
			};

			var token = new JwtSecurityToken(
				issuer: issuer,
				audience: audience,
				claims: claims,				
				signingCredentials: credentials);			

			return new JwtSecurityTokenHandler().WriteToken(token);
		}

		/// <summary>
		/// 从token获取值
		/// </summary>
		/// <param name="token"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string? GetValueFromJwtToken(string token, string key)
		{			
			return new JwtSecurityTokenHandler().ReadJwtToken(token).Claims.FirstOrDefault(c => c.Type == key)?.Value;
		}
	}
}
